<template>
  <transition name="slide-R" tag="div" class="c-martin__notification__contain">
    <div
      class="c-martin__notification"
      :style="{top: notif.top, zIndex: notif.zIndex}"
      v-if="showNotify"
    >
      <i class="iconfont" :ref="ref" @click="delNotification">&#xe751;</i>
      {{slotNotif.message}}
    </div>
  </transition>
</template>

<script>
export default {
  name: 'MartinNotification',
  props: {
    notifications: {
      type: Array,
      default: () => [],
      required: false
    }
  },
  data() {
    return {
      showNotify: false,
      notif: {
        top: '40px',
        zIndex: 1,
        toString() {
          return this.top + this.zIndex
        }
      },
      slotNotif: {
        duration: 3000
      },
      timer: null
    }
  },
  methods: {
    showNotification(option) {
      this.slotNotif = option
      this.showNotify = true
      this.ref = this.notif + ''
      const NOTIFICATIONS = Array.from(document.getElementsByClassName('c-martin__notification'))
      if (NOTIFICATIONS.length) {
        const LATESTNOTIFCATION = NOTIFICATIONS.slice(-1)[0]
        this.notif.top = parseInt(LATESTNOTIFCATION.style.top, 10) + 170 + 'px'
        this.notif.zIndex = LATESTNOTIFCATION.style.zIndex + 1
      }
      if (this.slotNotif.duration) {
        this.initDuration()
      }
    },
    initDuration() {
      this.timer = setTimeout(_ => {
        this.delNotification()
        clearTimeout(this.timer)
      }, this.slotNotif.duration + 300)
    },
    delNotification(e) {
      this.showNotify = false
      const NOTIFICATIONS = Array.from(document.getElementsByClassName('c-martin__notification'))
      const target = e ? e.target : this.$refs[this.ref]
      if (NOTIFICATIONS.length) {
        const index = Array.prototype.indexOf.call(NOTIFICATIONS, target.parentNode)
        NOTIFICATIONS.forEach((val, i) => {
          if (i > index) {
            val.style.top = parseInt(val.style.top, 10) - 170 + 'px'
          }
        })
      }
    }
  }
}
</script>

<style scoped lang="less">
@import url("../assets/css/style.less");
</style>
